/**
@author		Jong Min, Lee
@date		  10/01/2014
@breif		Study set class and Producer class 

copyright(c) Tae Young Soft. All right reserved. 2014
*/
#include "stdafx.h"
#include "Taurus_DcmData/StudySet.h"

#include "Taurus_DcmData/Study.h"

CStudySet::CStudySet()
{
  init();
}

CStudySet::~CStudySet()
{
  removeAllStudies();
}

CStudy* CStudySet::getPrimaryStudy() const
{
  return m_thePrimaryStudy;
}

unsigned CStudySet::getNumStudies() const
{
  return m_theStudies.size();
}

CStudy* CStudySet::getStudy(const unsigned index) const
{
  if(index >= m_theStudies.size()) return nullptr;

  return m_theStudies[index];
}

void CStudySet::init()
{
  m_theOpenMode = StudySetOpenModeFirstInvalid;
  m_thePrimaryStudy = NULL;
}

void CStudySet::destroy()
{
  removeAllStudies();
}

void CStudySet::removeAllStudies()
{
  unsigned num = m_theStudies.size();
  for(unsigned i = 0; i < num; ++i)
    _DELETE(m_theStudies[i]);
  m_theStudies.clear();
  m_thePrimaryStudy = nullptr;
}
    
DWORD CStudySetProducer::produce(CStudy** studies, 
                                 const unsigned numStudies, 
                                 const unsigned primaryIndex, 
                                 StudySetOpenMode openMode, 
                                 CStudySet*& outStudySet)
{
  if(openMode <= StudySetOpenModeFirstInvalid ||
     openMode >= StudySetOpenModeLastInvalid)
     return ERROR_INVALID_PARAMETER;

  if(studies == nullptr || numStudies == 0) return ERROR_INVALID_PARAMETER;

  if(numStudies <= primaryIndex) return ERROR_INVALID_PARAMETER;

  CStudySet* newStudySet = NULL;
  _TRY_ALLOC(newStudySet, CStudySet);
  if(newStudySet == NULL) return ERROR_NOT_ENOUGH_MEMORY;

  newStudySet->m_theOpenMode = openMode;
  newStudySet->m_thePrimaryStudy = studies[primaryIndex];

  _TRY_BEGIN
  newStudySet->m_theStudies.reserve(numStudies);
  _CATCH_ALL
  _DELETE(newStudySet);
  return ERROR_NOT_ENOUGH_MEMORY;
  _CATCH_END

  for(unsigned i = 0; i < numStudies; ++i)
  {
    if(studies[i] == NULL) continue;;
    newStudySet->m_theStudies.push_back(studies[i]);
    studies[i]->setParent(newStudySet);
  }

  if(newStudySet->m_theStudies.size() == 0 ||
     newStudySet->m_thePrimaryStudy == NULL)
  {
    _DELETE(newStudySet);
    return ERROR_INVALID_PARAMETER;
  }

  outStudySet = newStudySet;
  return ERROR_SUCCESS;
}